<template>
  <n-modal v-model:show="showUploader">
    <n-card
      style="width: 600px"
      title="导入用户"
      size="huge"
      :bordered="false"
      role="dialog"
      aria-modal="true"
      closable
      @close="handleClose"
    >
      <n-upload
        multiple
        directory-dnd
        accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        :headers="headers"
        :data="data"
        :action="importUrl"
        :max="3"
        :show-remove-button="false"
        @before-upload="beforeUpload"
        @finish="finish"
      >
        <n-upload-dragger>
          <div style="margin-bottom: 12px">
            <n-icon size="48" :depth="3">
              <archive-icon/>
            </n-icon>
          </div>
          <n-text style="font-size: 16px">
            点击或者拖动文件到该区域来上传
          </n-text>
          <n-p depth="3" style="margin: 8px 0 0 0" class="cursor-pointer">
            单次只能上传一个xlsx格式的文件，且文件小于10M
          </n-p>
        </n-upload-dragger>
      </n-upload>
      <n-p depth="3" style="margin: 8px 0 0 0" class="cursor-pointer">
        <span @click="downloadTemplate">下载模版</span>
      </n-p>
    </n-card>
  </n-modal>
</template>

<script lang="ts">
import {defineComponent, ref} from 'vue'
import {ArchiveOutline as ArchiveIcon} from '@vicons/ionicons5'
import axios from "axios";
import {useUserStore} from "@/store/modules/user";
import { useMessage, UploadFileInfo } from 'naive-ui';
import {ResultEnum} from "@/enums/httpEnum";

export default defineComponent({
  components: {
    ArchiveIcon
  },
  setup() {
    const message = useMessage();
    const userStore = useUserStore();
    const showUploader = ref(false);

    const importUrl = import.meta.env.VITE_GLOB_API_URL + '/api/user/import';
    const headers = {
      Authorization: userStore.getToken,
    }
    const data = {
      tag: import.meta.env.VITE_APP_DEFAULT_TAG,
    }

    async function beforeUpload(data: {
      file: UploadFileInfo
      fileList: UploadFileInfo[]
    }) {
      if (data.file.file?.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        message.warning('只能上传xlsx格式的文件')
        return false
      }
      if (data.file.file?.size > 5 * 1024 * 1024) {
        message.warning('文件大小不能超过5M')
        return false
      }

      // 创建FormData
      const formData = new FormData()
      formData.append('file', data.file.file);

      // 发送POST请求
      const checkRes = await axios.post('/api/user/import/check', formData, {
        baseURL: import.meta.env.VITE_GLOB_API_URL, // 指定服务器地址
        headers: {
          Authorization: userStore.getToken,
        }
      });
      if (!checkRes) return false;
      const resData = checkRes.data;
      if (resData.code === 200) {
        return true;
      }
      else {
        message.error(resData.msg);
        return false;
      }
    }

    function finish({ event: Event }) {
      const res = eval('(' + Event.target.response + ')');
      const { code } = res;
      const _message = res.msg || res.message || '上传失败';
      //成功
      if (code === ResultEnum.SUCCESS) {
        message.success(_message);
      } else {
        message.error(_message)
      }
    }

    const downloadTemplate = async () => {
      try {
        let res = await axios.post('/api/user/export/template', {}, {
          baseURL: import.meta.env.VITE_GLOB_API_URL, // 指定服务器地址
          responseType: 'blob',
          headers: {
            Authorization: userStore.getToken,
          }
        });
        // 获取http头部的文件名信息，若无需重命名文件，将下面这行删去
        // const fileName = res.headers["content-disposition"].split("=")[1];
        const fileName = '人员列表导入模版';
        /* 兼容ie内核，360浏览器的兼容模式 */
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          const blob = new Blob([res.data], {
            type: res.headers['content-type']
          });
          window.navigator.msSaveOrOpenBlob(
            blob,
            decodeURIComponent(fileName)
          );
        } else {
          /* 火狐谷歌的文件下载方式 */
          const blob = new Blob([res.data], {
            type: res.headers['content-type']
          });
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement("a"); // 创建a标签
          link.href = url;
          link.download = decodeURIComponent(fileName); // 文件重命名，若无需重命名，将该行删去
          link.click();
          URL.revokeObjectURL(url); // 释放内存
        }
      } catch (error) {
        console.error(error);
      }
    }

    const handleClose = () => {
      showUploader.value = false;
    }

    return {
      showUploader,
      importUrl,
      headers,
      data,
      beforeUpload,
      finish,
      downloadTemplate,
      handleClose,
    }
  }
})
</script>
